/*
 기능 : 친구추가레이아웃
 작성 : 하드캔
 완료일 : 2014.09.26 
 	*/
package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

public class AddFriendActivity extends BaseActivity {

	EditText search_id;
	
	EditText editID;
	EditText editName;
	EditText editPhone;
	EditText editEmail;
	
	String name = "";
	String phone = "";
	String email = "";
	
	Intent mIntent;
	String userID;
	String find_result = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_friend);
		
		/*각각의 id를 객채로 만들어 받아온다*/
		userID = getIntent().getExtras().getString("userID");
		search_id = (EditText)this.findViewById(R.id.search_id);
		editID = (EditText)this.findViewById(R.id.editID);
		editName = (EditText)this.findViewById(R.id.editName);
		editPhone = (EditText)this.findViewById(R.id.editPhone);
		editEmail = (EditText)this.findViewById(R.id.editEmail);

		LinearLayout find_friend_view = (LinearLayout) findViewById(R.id.find_friend_view);
		find_friend_view.setVisibility(View.GONE);
		
		LinearLayout not_find_friend_view = (LinearLayout) findViewById(R.id.not_find_friend_view);
		not_find_friend_view.setVisibility(View.GONE);
		
		/*버튼을 눌렀을 시 각각의 기능*/
		findViewById(R.id.search).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(search_id.getWindowToken(),0); 
						if(search_id.getText().toString().equals(userID) == true)
						{
							new AlertDialog.Builder(AddFriendActivity.this).setTitle("자기자신을 검색하였습니다.")
							.setNeutralButton("뒤로", null).show();
						}
						else
						{
							name = "";
							phone = "";
							email = "";
							readUserInfoAsync myTask = new readUserInfoAsync();
							myTask.execute();
						}
					}
				});
		findViewById(R.id.register_btn).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						sendFriendInfoAsync myTask2 = new sendFriendInfoAsync();
						myTask2.execute();					
					}
				});
		findViewById(R.id.cancel_btn).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						LinearLayout find_friend_view = (LinearLayout) findViewById(R.id.find_friend_view);
						find_friend_view.setVisibility(View.GONE);
						
						LinearLayout not_find_friend_view = (LinearLayout) findViewById(R.id.not_find_friend_view);
						not_find_friend_view.setVisibility(View.GONE);
					}
				});
		
		getActionBar().setTitle("Post Memories");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayHomeAsUpEnabled(true);

	}
	
	public void attemptSearch(String find_result) {
		if(find_result.equals("success"))
		{
			LinearLayout not_find_friend_view = (LinearLayout) findViewById(R.id.not_find_friend_view);
			not_find_friend_view.setVisibility(View.GONE);

			LinearLayout find_friend_view = (LinearLayout) findViewById(R.id.find_friend_view);
			find_friend_view.setVisibility(View.VISIBLE);
			
			editID.setText(search_id.getText());

    		editName.setText(name);
    		editPhone.setText(phone);
    		editEmail.setText(email);
		}
		else
		{
			LinearLayout find_friend_view = (LinearLayout) findViewById(R.id.find_friend_view);
			find_friend_view.setVisibility(View.GONE);

			LinearLayout not_find_friend_view = (LinearLayout) findViewById(R.id.not_find_friend_view);
			not_find_friend_view.setVisibility(View.VISIBLE);
		}	
	}
	
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	/*아이템을 선택했을시 각각의 기능*/     
	    switch(item.getItemId()){
	    
	    case android.R.id.home:
            onBackPressed();
            break;

	    default:
	        return false;
	    }
	    return true;
	}
	
	protected String[] load_user_info(Context context){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/get_user_info.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);
       		conn.setReadTimeout(15000);
       		conn.setDefaultUseCaches(false);
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);  
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              
         	StringBuffer buffer = new StringBuffer();
         	
         	buffer.append("user_id").append("=").append(search_id.getText());
         	
            
            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
           
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();

           
           	pString =  builder.toString();
           	Log.d("pString", pString);
           	if(pString.equals("[]"))
           		find_result = "fail";
           	else
           		find_result = "success";
           	
           	JSONObject jObject = new JSONObject(pString);
           	JSONArray nameObject = new JSONArray(jObject.getString("name"));
           	JSONArray phoneObject = new JSONArray(jObject.getString("phone"));
           	JSONArray emailObject = new JSONArray(jObject.getString("email"));
           	
           
           	name = nameObject.getString(0);
           	phone = phoneObject.getString(0);
           	email = emailObject.getString(0);           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	
	public class readUserInfoAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {

			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			load_user_info(AddFriendActivity.this);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			
			attemptSearch(find_result);
			
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
	
	/*서버와 연동하여 친구정보를 보낸다*/
	protected String[] send_friend_info(Context context){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/make_friend.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(15000);
       		conn.setReadTimeout(15000);
       		conn.setDefaultUseCaches(false);
           	conn.setDoInput(true);
           	conn.setDoOutput(true); 
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                       	
         	StringBuffer buffer = new StringBuffer();
         	
         	buffer.append("user_id").append("=").append(userID).append("&");
         	buffer.append("friend_id").append("=").append(search_id.getText().toString());

         	
            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
           
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();

           
           	pString =  builder.toString();
           	Log.d("pString", pString);
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	
	public class sendFriendInfoAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {

        	super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			send_friend_info(AddFriendActivity.this);
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			
			new AlertDialog.Builder(AddFriendActivity.this).setTitle(search_id.getText()+"친구등록을 완료하였습니다.")
			.setNeutralButton("확인", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					onBackPressed();
				}
			}).show();

			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}


}
